/**
 * SystemServer.java
 * com.sitech.system.server.service
 * Function： TODO 
 *
 *   ver  author   date    
 * ──────────────────────────────────
 *   	 geutopia  Feb 11, 2011        
 *
 * Copyright (c) 2011, TNT All Rights Reserved.
*/

package com.sitech.server.service;

import java.net.URL;
import java.util.Date;

import javax.servlet.ServletContext;

import com.sitech.server.ServerStart;
import com.sitech.service.SerialService;
import com.sitech.server.domain.ServerInfo;

/**
 * ClassName:SystemServer
 * Function: TODO ADD FUNCTION
 * Reason:	 TODO ADD REASON
 *
 * @author   geutopia
 * @version  
 * @since    Ver 1.1
 * @Date	 2011	Feb 11, 2011		4:59:17 PM
 *
 * @see 	 
 */

public class SystemServer implements ServerStart
{
	private int orderNo;
	private ServerService serverService;
	private SerialService serialService;

	/**
	 * (non-Javadoc)
	 * @see com.sitech.server.ServerStart#start()
	 */
	public void start()
	{
		start("");
	}

	/**
	 * (non-Javadoc)
	 * @see com.sitech.server.ServerStart#start(javax.servlet.ServletContext)
	 */
	public void start(ServletContext context)
	{
		try
		{
			URL bb = context.getResource("/");
			String ss = bb.toString();
			int vv = ss.lastIndexOf("/", ss.length()-2);
			String contextPath = ss.substring(vv+1,ss.length()-1);	
			start(contextPath);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	private void start(String context)
	{
		if(context == null || "".equals(context.trim()))
		{
			context = null;
		}
		
		ServerInfo localServer = serverService.getLocalServer();
		ServerInfo serverInfo = serverService.getServer(localServer.getServerIp(), localServer.getServerPort(),context);
		
		if(serverInfo == null)
		{
			localServer.setStatus(serverService.SERVER_STATUS_UP);
			localServer.setServerId(serialService.newSerialNo(null));
			localServer.setServerContext(context);
			serverService.insertServer(localServer);
		}
		else
		{
			serverInfo.setLastUpTime(new Date());
			serverInfo.setStatus(serverService.SERVER_STATUS_UP);
			serverService.updateServer(serverInfo);
			serverService.setLocalServer(serverInfo);
		}
	}

	public ServerService getServerService()
	{
		return serverService;
	}

	public void setServerService(ServerService serverService)
	{
		this.serverService = serverService;
	}

	public SerialService getSerialService()
	{
		return serialService;
	}

	public void setSerialService(SerialService serialService)
	{
		this.serialService = serialService;
	}

	public int getOrderNo()
	{
		return orderNo;
	}

	public void setOrderNo(int orderNo)
	{
		this.orderNo = orderNo;
	}

}
